const axios = require('axios');

//http request 拦截器
//添加请求拦截器
axios.interceptors.request.use(config => {

    let token = sessionStorage.getItem('token');
    // 判断是否存在token，如果存在的话，则每个http header都加上token
    if (token) { config.headers = {'authorization': token }; }

    return config
},
err => {
  return Promise.reject(err)
});

// POST 请求方式
let postAction = function(url, params) {
    return new Promise((resolve, reject)=> {
        axios.post(url, params)
        .then(res=> { resolve(res.data) })
        .catch(error=>{ reject(error);  })
    });
}

// DELETE 请求方式
let deleteAction = function(url, params) {
    return new Promise((resolve, reject)=> {
        axios.delete(url, { data: params })
        .then(res=> { resolve(res.data) })
        .catch(error=>{ reject(error);  })
    });
}

// PUT 请求方式
let putAction = function(url, params) {
    return new Promise((resolve, reject)=> {
        axios.put(url, params)
        .then(res=> { resolve(res.data) })
        .catch(error=>{ reject(error);  })
    });
}

// GET 请求方式
let getAction = function(url, params) {
    return new Promise((resolve, reject)=> {
        axios.get(url, params)
        .then(res=> { resolve(res.data) })
        .catch(error=>{ reject(error);  })
    });
}


export default {
    postAction,
    deleteAction,
    putAction,
    getAction,
}